package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.MD5Util2;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Stream;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private MenuDao menuDao;

//    @Autowired
//    private JedisPool jedisPool;

    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }

    //分页查询
    @Override
    public PageResult findPage(Integer pageNum, Integer sizeNum, String queryString) {
        PageHelper.startPage(pageNum, sizeNum);
        Page<User> page = userDao.findPage(queryString);

        List<User> results = page.getResult();

        return new PageResult(page.getTotal(), page.getResult());
    }

    //新增用户
    @Override
    public void saveUser(User user, Integer[] roleIds) {

        //将图片保存到redis集合中
////        String filename = user.getImg();
////        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,filename);
        String password = user.getPassword();

        //创建密码加密对象,与security框架的加密格式相同
        BCryptPasswordEncoder bcpe = new BCryptPasswordEncoder();
        //对前台用户密码进行加密
        String passwordEncode = bcpe.encode(password);
        user.setPassword(passwordEncode);
        userDao.add(user);

        Integer userId = user.getId();
        setUserAndRole(userId, roleIds);

    }

    //编辑回显用户
    @Override
    public User findById(Integer id) {
        return userDao.findUserById(id);
    }

    //建立检查组和检查项多对多关系(抽取代码)
    public void setUserAndRole(Integer userId, Integer[] roleIds) {

        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                roleDao.setUserAndRole(map);
            }
        }
    }

    //编辑回显角色数据
    @Override
    public Integer[] findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    //编辑修改数据
    @Override
    public void updateUser(User user, Integer[] roleIds) {
        userDao.update(user);
        userDao.deleteRoleIdsByUserId(user.getId());
        Integer userId = user.getId();
        setUserAndRole(userId, roleIds);
    }

    //删除用户
    @Override
    public void deleteUser(Integer id) {
        userDao.deleteUserAndRole(id);
        userDao.delete(id);
    }

    //查询用户对应的菜单
    @Override
    public List<Menu> findByUsername01(String username) {
        User user = userDao.findWithMenusByUsername(username);
        List<Menu> menuList = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            LinkedHashSet<Menu> menus = role.getMenus();
            for (Menu menu : menus) {
                menuList.add(menu);
            }
        }

        return menuList;
    }

    /**
     * 修改用户状态
     *
     * @param userId
     * @param station
     */
    @Override
    public void updateStation(Integer userId, Integer station) {
        Map<String, Integer> map = new HashMap<>();
        map.put("userId", userId);
        map.put("station", station);
        userDao.updateStatus(map);
    }

    @Override
    public User findByTelephone(String telephone) {
        return userDao.findByTelephone(telephone);
    }

    @Override
    public void updatePassword(Integer id, String password01) {
        //创建密码加密对象,与security框架的加密格式相同
        BCryptPasswordEncoder bcpe = new BCryptPasswordEncoder();
        //对前台用户密码进行加密
        String passwordEncode = bcpe.encode(password01);
        userDao.updatePassword(id, passwordEncode);
    }

    @Override
    public List<User> findHealth() {
        return userDao.findHealth();
    }

    @Override
    public String findImg(String username) {
        return userDao.findImg(username);
    }


}